/**
 * 权限申请状态管理
 */
import { defineStore } from 'pinia'
import { PermissionRequestService } from '../services/permissionRequest'

export const usePermissionRequestsStore = defineStore('permissionRequests', {
  state: () => ({
    requests: [],
    loading: false,
    error: null,
    selectedRequest: null,
    // 管理员视图
    allRequests: [],
    allRequestsLoading: false
  }),

  getters: {
    // 获取待处理的申请
    pendingRequests: (state) => state.requests.filter(r => r.status === 'pending'),
    
    // 获取已批准的申请
    approvedRequests: (state) => state.requests.filter(r => r.status === 'approved'),
    
    // 获取已拒绝的申请
    rejectedRequests: (state) => state.requests.filter(r => r.status === 'rejected'),
    
    // 获取已取消的申请
    cancelledRequests: (state) => state.requests.filter(r => r.status === 'cancelled'),
    
    // 根据ID获取申请
    getRequestById: (state) => (id) => {
      return state.requests.find(r => r.id === id)
    },
    
    // 检查是否已申请某权限
    hasRequestedPermission: (state) => (permission) => {
      return state.requests.some(r => 
        r.permission === permission && 
        (r.status === 'pending' || r.status === 'approved')
      )
    }
  },

  actions: {
    /**
     * 获取我的权限申请
     */
    async fetchMyRequests(params = {}) {
      this.loading = true
      this.error = null
      
      try {
        // 注意：这里使用模拟数据，因为后端可能还没有实现该接口
        // 在实际环境中应该调用：const response = await PermissionRequestService.getMyRequests(params)
        
        // 模拟数据
        const mockRequests = [
          {
            id: '1',
            permission: 'ticket:assign',
            role: null,
            reason: '需要为团队分配工单',
            targetResource: '/ticket-management',
            status: 'pending',
            createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),
            updatedAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
          }
        ]
        
        this.requests = mockRequests
        console.log('✅ 获取我的权限申请成功')
      } catch (error) {
        this.error = error.message
        console.error('❌ 获取权限申请失败:', error)
      } finally {
        this.loading = false
      }
    },

    /**
     * 提交权限申请
     */
    async submitRequest(requestData) {
      this.loading = true
      this.error = null
      
      try {
        // 注意：这里使用本地存储模拟，实际应调用：
        // const response = await PermissionRequestService.submitRequest(requestData)
        
        const newRequest = {
          id: Date.now().toString(),
          ...requestData,
          status: 'pending',
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString()
        }
        
        this.requests.push(newRequest)
        
        console.log('✅ 权限申请已提交:', newRequest)
        return { success: true, data: newRequest }
      } catch (error) {
        this.error = error.message
        console.error('❌ 提交权限申请失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 取消权限申请
     */
    async cancelRequest(id) {
      this.loading = true
      this.error = null
      
      try {
        // const response = await PermissionRequestService.cancelRequest(id)
        
        const request = this.requests.find(r => r.id === id)
        if (request) {
          request.status = 'cancelled'
          request.updatedAt = new Date().toISOString()
        }
        
        console.log('✅ 权限申请已取消')
        return { success: true }
      } catch (error) {
        this.error = error.message
        console.error('❌ 取消权限申请失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 获取所有权限申请（管理员）
     */
    async fetchAllRequests(filters = {}) {
      this.allRequestsLoading = true
      this.error = null
      
      try {
        // const response = await PermissionRequestService.listAllRequests(filters)
        
        // 模拟数据
        this.allRequests = this.requests
        
        console.log('✅ 获取所有权限申请成功')
      } catch (error) {
        this.error = error.message
        console.error('❌ 获取权限申请列表失败:', error)
      } finally {
        this.allRequestsLoading = false
      }
    },

    /**
     * 批准权限申请（管理员）
     */
    async approveRequest(id, comment = '') {
      this.loading = true
      this.error = null
      
      try {
        // const response = await PermissionRequestService.approveRequest(id, comment)
        
        const request = this.allRequests.find(r => r.id === id)
        if (request) {
          request.status = 'approved'
          request.approvedComment = comment
          request.updatedAt = new Date().toISOString()
        }
        
        console.log('✅ 权限申请已批准')
        return { success: true }
      } catch (error) {
        this.error = error.message
        console.error('❌ 批准权限申请失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 拒绝权限申请（管理员）
     */
    async rejectRequest(id, reason = '') {
      this.loading = true
      this.error = null
      
      try {
        // const response = await PermissionRequestService.rejectRequest(id, reason)
        
        const request = this.allRequests.find(r => r.id === id)
        if (request) {
          request.status = 'rejected'
          request.rejectReason = reason
          request.updatedAt = new Date().toISOString()
        }
        
        console.log('✅ 权限申请已拒绝')
        return { success: true }
      } catch (error) {
        this.error = error.message
        console.error('❌ 拒绝权限申请失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    /**
     * 选择申请
     */
    selectRequest(request) {
      this.selectedRequest = request
    },

    /**
     * 清除选择
     */
    clearSelection() {
      this.selectedRequest = null
    }
  }
})

